# -*- coding: utf-8 -*-
'''
Copyright(C) 2013 "Kevin Xu <ssonxu@gmail.com>"

This file is part of acqu-center.

acqu-center is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

acqu-center is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with acqu-center.  If not, see <http://www.gnu.org/licenses/>.
'''
import os
import jinja2
import logging
import urllib
from modules.box import Box
from modules.contact import Contact as Con
from modules.Predef import Predef as PRE
from google.appengine.api import users

class Main:
        
    ####################################################
    # Initialize
    ####################################################
    def __init__(self, context):
        self.context=context
        self.user= users.get_current_user()
        #self.request=request
        #self.response=response
        self.message=''
        self.errmessage=''

        self.door=self.context.request.get('doorplate')

    ####################################################
    # For message
    ####################################################
    def MESSAGE(self,m):
        self.message=PRE.genMessage(self.message,m)

    def ERRMESSAGE(self,m):
        self.errmessage=PRE.genMessage(self.errmessage,"ERROR:"+m)

    ####################################################
    # Show the content
    ####################################################
    def getContent(self, t):
        temp_path=os.path.join(
                os.path.dirname(__file__),
                "../templates/")

        temp=jinja2.Environment(loader=jinja2.FileSystemLoader(temp_path)).get_template(t)

        if self.user:
            u = '%s <a href="%s"> sign out </a>' % ( self.user.nickname(), users.create_logout_url("/"))
        else:
            u = 'guest'
        # for main page
        if self.door == '':
            return temp.render(
                    {
                        'doors':PRE.doors,
                        'user': u,
                        })
        # came in to door
        else:

            return temp.render(
                    {
                        'doors':PRE.doors,
                        'user': u,
                        'candidates':self.candidates,
                        'doorplate':self.door,
                        'e':self.errmessage,
                        'm':self.message,
                        'subs':Con.getCon(self.user.email()).subs,
                        'isAdmin':users.is_current_user_admin(),
                        'isRunning':self.door==PRE.doors[0],
                        })


    ####################################################
    # Read and Check settings to GET
    ####################################################
    def doGet(self):
        if self.door == '':
            self.context.response.out.write(self.getContent('main.html'))
        else:

            if Con.getCon(self.user.email()) is None:
                logging.info("Create a new user %s", self.user.email())
                Con.addUser(self.user.email())

            self.candidates=Box.listBoxes(self.door==PRE.doors[0])
            self.context.response.out.write(self.getContent('door.html'))

    ####################################################
    # Read and Check settings to POST
    ####################################################
    def doPost(self):
        if self.door == '':
            self.context.response.out.write(self.getContent('main.html'))
        else:
            Me=Con.getCon(self.user.email())

            for k in Box.listBoxes(self.door==PRE.doors[0]):
                if self.context.request.get('hidden_'+str(k.ID())) == 'Deleted':
                    Box.delBoxByID(k.ID())
                    self.MESSAGE('Success: "{}" has been deleted!'.format(k.label))
                if self.context.request.get('check_'+str(k.ID())) == 'Checked': 
                    if k.ID() not in Me.subs:
                        Me.subs.append(k.ID())
                        self.MESSAGE('Success: You have subscripted the "{}"!'.format(k.label))
                else:
                    if k.ID() in Me.subs:
                        Me.subs.remove(k.ID())
                        self.MESSAGE('Success: You have unsubscripted the "{}"!'.format(k.label))

            Me.put()
            self.candidates=Box.listBoxes(self.door==PRE.doors[0])

            label=self.context.request.get('newlabel')

            if (label!=''):

                if Box.getBox(label):
                    self.ERRMESSAGE('"{}" has existed in current list'.format(label))
                else:
                    self.context.redirect('/cell?label='+urllib.quote(label.encode('utf-8')))

            self.context.response.out.write(self.getContent('door.html'))
